<?php
/**
 * article table
 * 'title', 'short_title', 'descrition', 'image_id', 'image_id_list', 'content', 'uid'
 *
 */
namespace backend\models;

use Yii;
use yii\db\ActiveRecord;
class Category extends ActiveRecord{
    public static $tree = ['顶级分类'];
    public static $lists = [];
	public function scenarios(){
		return [
			'create' => ['name', 'pid', 'order', 'create_time','is_show', 'status'],

			'update' => ['name', 'pid', 'order', 'create_time','is_show', 'status'],
		];
	}

	public function rules(){

		return [
			[['name', 'order'], 'required'],
			['name', 'string', 'min' => 1, 'max' => 20],
			['pid', 'default', 'value' => 0, 'skipOnEmpty' => false, 'skipOnError' => false],
			//['pid', 'exist', 'targetClass' => Category::className(), 'targetAttribute' => ['pid'=> 'id']],
			['order', 'integer'],
			['create_time', 'default', 'value' => time(),],
            ['is_show', 'in', 'range'=>[0,1]],
            ['status', 'in', 'range' => [0,10]],
		];
	}

    public function attributeLabels(){
        return [
            'name' => '分类名称',
            'order' => '排序',
            'pid' => '上级分类',
            'is_show' => '是否显示',
            'status' => '状态',
            'create_time' => '创建时间',
        ];
    }

    public static function getData()
    {
        return self::find()->asArray()->all();
    }

    public static function getCatTree($cats , $pid = 0, $nu = 0 )
    {
        $bx = '---|' ;
        $nu++ ;
        foreach ($cats as $cat){
            $catid		= $cat['id'];
            $catname	= $cat['name'];
            $catpid		= $cat['pid'];
            if ($catpid == $pid) {
                self::$tree[$catid] = str_repeat($bx, $nu) .'~'. $catname . PHP_EOL  ;
                self::getCatTree($cats, $catid, $nu ) ;
            }
        }
    }

    public static function tree() {
        $cats = self::getData();
        self::getCatTree($cats, 0, 0);
        return self::$tree;
    }

    public static function getLvLists($cats, $pid = 0, $nu = 0 ){
        $bx = '---|' ;
        $nu++ ;
        foreach ($cats as $key => $cat){
            if ($cat['pid'] == $pid) {
                $cat['name'] = str_repeat($bx, $nu) .'~'. $cat['name'] . PHP_EOL;
                self::$lists[] = $cat;
                unset($cats[$key]);
                self::getLvLists($cats, $cat['id'], $nu);
            }
        }
        return self::$lists;
    }
}